layui.config({
    version: true,   // 更新组件缓存，设为true不缓存，也可以设一个固定值
    base: 'assets/module/'
}).extend({
    soulTable: 'soulTable/soulTable.slim',
    tableChild: 'soulTable/tableChild',
    tableMerge: 'soulTable/tableMerge',
    tableFilter: 'soulTable/tableFilter',
    excel: 'soulTable/excel',
    formSelects: 'formSelects/formSelects-v4',
    treetable: 'treetable-lay/treetable',
    dropdown: 'dropdown/dropdown',
    notice: 'notice/notice',
    step: 'step-lay/step',
    dtree: 'dtree/dtree',
    citypicker: 'city-picker/city-picker',
    tableSelect: 'tableSelect/tableSelect',
    cropper: 'cropper/cropper',
    zTree: 'zTree/zTree',
    IconFonts: 'iconFonts/iconFonts',
    newTree: 'treeTable/treeTable',
    authtree: 'authtree/authtree'
}).use(['config', 'layer', 'element', 'index', 'admin', 'laytpl'], function () {
    var $ = layui.jquery;
    var layer = layui.layer;
    var element = layui.element;
    var config = layui.config;
    var index = layui.index;
    var admin = layui.admin;
    var laytpl = layui.laytpl;

    // 搜索栏的收起展开点击事件
    $("body").delegate(".spread-btn","click",function (dom) {
        // config.putOn("spread-btn",dom);
        let that = $(this);
        let layQueryContent = that.parent('.lay-spread-box').siblings().find('.lay-query-content');
        if (that.hasClass('is-spread')) {
            that.removeClass('is-spread');
            layQueryContent.removeClass('query-ht-auto');
            layQueryContent.height('43px');
            that.find('.spread-span').text('展开');
        } else {
            let ht = that.parent('.lay-spread-box').siblings().find('.query-lt').height();
            that.addClass('is-spread');
            layQueryContent.addClass('query-ht-auto');
            layQueryContent.height(ht);
            that.find('.spread-span').text('收起');
        }
    });

    // 检查是否登录
    if (!config.getToken()) {

        return location.replace('/admin/login.html');
    }

    // 获取用户信息
    admin.req('user/admin/login/userInfo', {}, function (res) {
        if (200 == res.code) {
            console.log(1213,res.data);
            
            $('#huName').text(res.data.username+'('+res.data.nickname+')');
            config.putUser(res.data);
        } else {
            // 返回登录页
            // location.replace('/admin/login.html');
        }
    }, 'get');

    // 加载侧边栏
    admin.reqSync('user/admin/login/menu', {}, function (res) {
        if(res.code != 200){
            location.replace('/admin/login.html');
        }
        let flagIndex = config.getTempData('menuIndex');
        res.data.forEach(function (item, index){
            item.isShow = index === flagIndex ? true : false;
            if (index == 0 && flagIndex == '') {
                item.isShow = true;
            }
            // if (item.name == '系统管理' && flagIndex === '') {
            //     item.isShow = true;
            // }
            laytpl(sideNav.innerHTML).render(item, function (html) {
                $('.layui-layout-admin .layui-side .layui-side-scroll').append(html);
                element.render('nav');
            });
        });
        laytpl(sideNav2.innerHTML).render(res.data, function (html) {
            $('.layui-nav.layui-layout-left.menu').html(html);
            element.render('nav');
        });
        var origin = window.location.href;
        var urlCode = origin.substr(origin.lastIndexOf('//') + 2, 5);
        var url = urlCode=='e0036' ? '#/bill/weighCabinetReport' : '#/bill/workshopReport';

        index.regRouter(res.data);  // 注册路由
        index.loadHome({  // 加载主页
            url: url,
            name: '<i class="layui-icon layui-icon-home"></i>'
        });
        config.putUserMenu(res.data);
    }, 'get');

    // 移除loading动画
    setTimeout(function () {
        admin.removeLoading();
    }, 300);

    // 提示
    // if (!config.pageTabs) {
    //     layer.confirm('SPA版本默认关闭多标签功能，你可以在设置界面开启', {
    //         skin: 'layui-layer-admin',
    //         area: '280px',
    //         title: '温馨提示',
    //         shade: 0,
    //         btn: ['打开设置', '知道了']
    //     }, function (i) {
    //         layer.close(i);
    //         $('a[ew-event="theme"]').trigger('click');
    //     });
    // }

    // 从index.html 挪动过来的js
    $(".layui-nav.layui-layout-left.menu").delegate("li", "click", function () {
        let liName = $(this).data("name");
        // if(liName=='可视化面板'){
        //     var domain=window.location.origin;
        //     var enterpriseCode=domain.substr(domain.indexOf("//")+2,5)
        //     var location=domain.substr(domain.indexOf("//")+2,(domain.length-domain.indexOf("//")-2))
        //     window.open('http://'+enterpriseCode+'.yunduanzhizao.com/index?url='+location);
        // }
        config.putTempData('menuIndex', $(this).index());
        $(this).addClass('nav-active').siblings().removeClass('nav-active');
        $(".layui-nav.layui-nav-tree").each(function (index, element) {
            let dataName = $(element).data("name");
            if (dataName == liName) {
                $(element).removeClass("layui-hide");
            } else {
                $(element).addClass("layui-hide");
            }
        })
    });

    // 通用流程指引
    $("body").delegate(".header-right-btn", "click", function () {
        $.each($(".layui-layout-left.menu li"), function (index, element) {
            if ($(this).text().trim() == '智能柜') {
                config.putTempData('menuIndex', index);
                $(".layui-layout-left.menu").find('li').removeClass('nav-active').eq(index).addClass('nav-active');
            }
        })
    });

    // 关闭详情侧边栏弹出
    $('.layui-header').click(function () {
        isDeitail();
    });
    $('.layui-side').click(function () {
        isDeitail();
    });
    $('.layui-body').click(function () {
        isDeitail();
    });

    function isDeitail() {
        if ($('div').hasClass('layui-open-detail')) {
            layer.closeAll();
        }
    }

    // 查询企业信息
    admin.req('user/admin/face/getEnterpriseInfo', {}, function (res) {
        if (res.code == 200) {
            img_path = res.data.enterpriseId + "/";
        } else {
            layer.msg('获取企业信息失败', {icon: 2, time: 1000});
        }
    }, 'GET');

    // 查询logo、版权信息等
    admin.req('enterprise/system/admin/systemOfficialInfo/getInfo', {}, res => {
        if (res.code === 200) {
            if (res.data.foregroundInverseLogo) {
                backgroundLogo = res.data.foregroundInverseLogo;
            }
            if (res.data.sysName) {
                adminTile = res.data.sysName;
            }
        }
        $('#headerBackgroundLogo').attr('src', backgroundLogo);
        $('#headerBackgroundLogo').css('opacity', 1);
        $("#adminTile").html(adminTile);
        $("#linkHref").attr('href', res.data.icon)
    }, 'GET');
    // 查询logo、版权信息等
    // admin.req('enterprise/system/admin/systemOfficialInfo/getEnterpriseCode', {enterpriseCode: getSubdomain()}, res => {
    //     if (res.code === 200) {
    //         if (res.data.foregroundInverseLogo) {
    //             backgroundLogo = res.data.foregroundInverseLogo;
    //         }
    //     }
    //     $('#headerBackgroundLogo').attr('src', backgroundLogo);
    //     $('#headerBackgroundLogo').css('opacity', 1);
    //     $("#adminTile").html(adminTile);
    //     $("#linkHref").attr('href', res.data.icon)
    // }, 'GET');

    /**
     * 获取当前 URL 二级域名
     * 如果当前是 IP 地址，则直接返回 IP Address
     */
    function getSubdomain() {
        try {
            let subdomain = '';
            const { domain } = document;
            const domainList = domain.split('.');
            const ipAddressReg = /^(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])$/;
            // 若为 IP 地址、localhost，则直接返回
            if (ipAddressReg.test(domain) || domain === 'localhost') {
                return domain
            }

            /* const urlItems = [];
             urlItems.unshift(domainList.pop());*/

            /*while (domainList.length) {
                urlItems.unshift(domainList.pop());
                subdomain = urlItems.join('.');
            }*/
            subdomain =  domainList[0] || document.domain;

            return subdomain
        } catch (e) {
            return document.domain
        }
    }
});
